import React, { useState, useEffect } from 'react';
import { Layout as AntLayout, Menu, Avatar, Dropdown, message } from 'antd';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import {
  DashboardOutlined,
  ShoppingOutlined,
  GiftOutlined,
  OrderedListOutlined,
  SelectOutlined,
  AppstoreOutlined,
  UserOutlined,
  BarChartOutlined,
  LogoutOutlined,
  SettingOutlined,
  ProfileOutlined,
} from '@ant-design/icons';
import { useDispatch, useSelector } from 'react-redux';
import { logout } from '../store/authSlice';
import routes from '../routes';

const { Header, Sider, Content } = AntLayout;

const Layout = ({ children }) => {
  const [collapsed, setCollapsed] = useState(false);
  const [currentPath, setCurrentPath] = useState('');
  const location = useLocation();
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const { userInfo, isAuthenticated } = useSelector((state) => state.auth);

  // 监听路由变化
  useEffect(() => {
    setCurrentPath(location.pathname);
  }, [location.pathname]);

  // 处理菜单点击
  const handleMenuClick = (e) => {
    const { key } = e;
    navigate(key);
  };

  // 处理登出
  const handleLogout = () => {
    dispatch(logout())
      .unwrap()
      .then(() => {
        message.success('登出成功');
        navigate('/login');
      })
      .catch(() => {
        message.error('登出失败');
      });
  };

  // 生成菜单项
  const renderMenuItems = () => {
    if (!isAuthenticated || !userInfo) {
      return [];
    }

    // 从路由配置中提取菜单项
    const menuRoutes = routes.find((route) => route.path === '/')?.routes || [];
    
    return menuRoutes.map((route) => ({
      key: route.path,
      icon: getIconByName(route.icon),
      label: <Link to={route.path}>{route.name}</Link>,
      disabled: !hasPermission(route.permissions),
    }));
  };

  // 根据名称获取图标组件
  const getIconByName = (iconName) => {
    const iconMap = {
      dashboard: <DashboardOutlined />,
      ticket: <ShoppingOutlined />,
      discount: <ShoppingOutlined />,
      gift: <GiftOutlined />,
      'ordered-list': <OrderedListOutlined />,
      box: <AppstoreOutlined />,
      user: <UserOutlined />,
      'bar-chart': <BarChartOutlined />,
    };
    return iconMap[iconName] || <DashboardOutlined />;
  };

  // 检查用户是否有指定权限
  const hasPermission = (permissions) => {
    // 如果没有指定权限要求，则所有用户都可以访问
    if (!permissions || permissions.length === 0) {
      return true;
    }

    // 管理员角色拥有所有权限
    if (userInfo?.role === 'ADMIN') {
      return true;
    }

    // 这里应该检查用户实际的权限列表
    // 简化处理，假设普通用户只有查看仪表盘的权限
    if (userInfo?.role === 'USER') {
      return permissions.includes('DASHBOARD_VIEW') || 
             permissions.includes('ANALYSIS_VIEW');
    }

    return false;
  };

  // 用户菜单
  const userMenu = (
    <Menu>
      <Menu.Item key="1" icon={<ProfileOutlined />}>
        个人信息
      </Menu.Item>
      <Menu.Item key="2" icon={<SettingOutlined />}>
        账户设置
      </Menu.Item>
      <Menu.Divider />
      <Menu.Item key="3" icon={<LogoutOutlined />} danger onClick={handleLogout}>
        退出登录
      </Menu.Item>
    </Menu>
  );

  return (
    <AntLayout style={{ minHeight: '100vh' }}>
      {/* 侧边栏 */}
      <Sider
        collapsible
        collapsed={collapsed}
        onCollapse={(value) => setCollapsed(value)}
        width={200}
        theme="dark"
      >
        <div className="logo" style={{ padding: '16px', color: 'white', fontSize: '18px', textAlign: 'center' }}>
          营销中心
        </div>
        <Menu
          mode="inline"
          selectedKeys={[currentPath]}
          onClick={handleMenuClick}
          style={{ height: '100%', borderRight: 0 }}
        >
          {renderMenuItems()}
        </Menu>
      </Sider>

      {/* 主内容区域 */}
      <AntLayout>
        {/* 顶部导航栏 */}
        <Header
          style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            padding: '0 24px',
            background: '#fff',
            boxShadow: '0 1px 4px rgba(0,21,41,.08)',
          }}
        >
          <div style={{ fontSize: '16px', fontWeight: 'bold' }}>
            营销中心管理系统
          </div>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <span style={{ marginRight: '16px' }}>欢迎，{userInfo?.name}</span>
            <Dropdown overlay={userMenu} placement="bottomRight">
              <Avatar src={userInfo?.avatar} alt={userInfo?.name} />
            </Dropdown>
          </div>
        </Header>

        {/* 内容区域 */}
        <Content
          style={{
            margin: '16px 24px',
            padding: 24,
            background: '#fff',
            minHeight: 280,
            borderRadius: 8,
          }}
        >
          {children}
        </Content>
      </AntLayout>
    </AntLayout>
  );
};

export default Layout;